package cn.schoolwow.flow.monitor.module.business.flowRecord.flow;

import cn.schoolwow.ams.module.block.listBlock.common.domain.operation.ListBlockRequest;
import cn.schoolwow.flow.monitor.domain.FlowMonitorOption;
import cn.schoolwow.flow.monitor.module.business.flowRecord.domain.FlowRecord;
import cn.schoolwow.flow.monitor.module.business.flowRecord.domain.FlowRecordContext;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instanceList.QueryInstanceList;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class ExecuteFlowRecordFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        ListBlockRequest listBlockRequest = flowContext.checkInstanceData(ListBlockRequest.class);
        ApplicationContext applicationContext = flowContext.checkInstanceData(ApplicationContext.class);
        FlowMonitorOption flowMonitorOption = applicationContext.getBean(FlowMonitorOption.class);

        List<FlowRecord> flowRecordList = new ArrayList<>();
        if(null!=listBlockRequest.array){
            flowRecordList.addAll(listBlockRequest.array.toJavaList(FlowRecord.class));
        }else{
            flowRecordList.add(listBlockRequest.row.toJavaObject(FlowRecord.class));
        }

        List<String> categoryNameList = QueryInstanceList.newQuery(flowRecordList)
                .execute()
                .getSingleFieldValueList("categoryName");
        flowContext.startFlow(new GetFlowRecordContextListFlow())
                .putCurrentCompositeFlowData("categoryNameList", categoryNameList)
                .execute();
        List<FlowRecordContext> list = flowContext.getData("list", List.class);
        if(null==list||list.isEmpty()){
            throw new IllegalArgumentException("流程记录查询为空!名称列表:"+categoryNameList);
        }
        for(FlowRecord flowRecord:flowRecordList){
            FlowRecordContext flowRecordContext = QueryInstanceList.newQuery(list)
                    .addQuery("categoryName", flowRecord.categoryName)
                    .addQuery("name", flowRecord.name)
                    .execute()
                    .getOne();
            if(null==flowRecordContext){
                throw new IllegalArgumentException("流程记录不存在!分类:"+flowRecord.categoryName+",名称:"+flowRecord.name);
            }
            flowMonitorOption.logQuickFlow.startFlow(flowRecordContext.flowRecordable).execute();
        }
    }

    @Override
    public String name() {
        return "执行流程记录流程";
    }
}
